package com.water.devtool;

import java.io.File;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import com.watermud.util.FileUtil;

public class ExportUtil {
	
	public static boolean exportToFile(String dir, String fileName,
			String content) {
		JFileChooser fc = new JFileChooser();
		fc.setCurrentDirectory(new File(dir));
		fc.setSelectedFile(new File(fileName));
		fc.setDialogType(JFileChooser.SAVE_DIALOG);
		int returnVal = fc.showOpenDialog(null);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();
			if (file.exists()) {
				Object[] options = { "替换", "追加" };
				int i = JOptionPane.showOptionDialog(null, "文件已经存在，请选择操作。。。",
						"Warning", JOptionPane.DEFAULT_OPTION,
						JOptionPane.WARNING_MESSAGE, null, options, options[0]);
				if (i == JOptionPane.CLOSED_OPTION) {
					return false;
				}
				if (i == 0) {
					file.delete();
				}
			}
			try {
				FileUtil.append(file, content);
				JOptionPane.showMessageDialog(null, "保存成功！",
						"information", JOptionPane.INFORMATION_MESSAGE);
				return true;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}

		return false;
	}
	
	public static boolean exportToFileNew(String dir, String fileName,
			String content) {
		JFileChooser fc = new JFileChooser();
		fc.setCurrentDirectory(new File(dir));
		fc.setSelectedFile(new File(fileName));
		fc.setDialogType(JFileChooser.SAVE_DIALOG);
		int returnVal = fc.showOpenDialog(null);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();
			if (file.exists()) {
					file.delete();
			}
			try {
				FileUtil.append(file, content);
				JOptionPane.showMessageDialog(null, "保存成功！",
						"information", JOptionPane.INFORMATION_MESSAGE);
				return true;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}

		return false;
	}
	
	public static boolean exportToFileAppend(String dir, String fileName,
			String content) {
		JFileChooser fc = new JFileChooser();
		fc.setCurrentDirectory(new File(dir));
		fc.setSelectedFile(new File(fileName));
		fc.setDialogType(JFileChooser.SAVE_DIALOG);
		int returnVal = fc.showOpenDialog(null);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();
			try {
				FileUtil.append(file, content,"GBK");
				JOptionPane.showMessageDialog(null, "保存成功！",
						"information", JOptionPane.INFORMATION_MESSAGE);
				return true;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}

		return false;
	}
	
}
